﻿using COSXML;
using COSXML.Auth;
using COSXML.Model.Object;
using COSXML.Transfer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SetSailModel;

namespace SetSailCommon
{
    /// <summary>
    /// Cos操作（对象存储）
    /// </summary>
    public class CosHelper
    {
        private CosXml cosXml;
        public CosHelper()
        {
            CosXmlConfig config = new CosXmlConfig.Builder()
              .SetRegion("ap-nanjing") // 设置默认的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224 
              .Build();


            long durationSecond = 600;          //每次请求签名有效时长，单位为秒
            QCloudCredentialProvider qCloudCredentialProvider = new DefaultQCloudCredentialProvider(CookieData.getInstance().secretId,
              CookieData.getInstance().secretKey, durationSecond);

            this.cosXml = new CosXmlServer(config, qCloudCredentialProvider);
        }

        public string result2 = "ok";
        /// <summary>
        /// 上传
        /// </summary>
        /// <param name="key"></param>
        /// <param name="path"></param>
        public void PutObjectStream(string key, string path)
        {
            try
            {
                //string key = "2022-06-11/HZH_Controls.rar"; //对象键 例如将 picture.png 上传到 doc 文件夹，则对象键设置为 doc/picture.png
                //string srcPath = @"C:\Users\15958\Desktop\HZH_Controls.rar";//本地文件绝对路径
                // 打开只读的文件流对象
                FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                // 组装上传请求，其中 offset sendLength 为可选参数
                long offset = 0L;
                long sendLength = fileStream.Length;
                PutObjectRequest request = new PutObjectRequest(CookieData.getInstance().bucket, key, fileStream, offset, sendLength);
                //设置进度回调
                //request.SetCosProgressCallback(delegate (long completed, long total)
                //{
                //    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
                //});
                //执行请求
                PutObjectResult result = cosXml.PutObject(request);
                //关闭文件流
                fileStream.Close();
                //对象的 eTag
                //string eTag = result.eTag;
                //对象的 crc64ecma 校验值
                //string crc64ecma = result.crc64ecma;
                //打印请求结果
                //Console.WriteLine(result.GetResultInfo());
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                result2 = "CosClientException: " + clientEx;
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                result2 = "CosServerException: " + serverEx.GetInfo();
            }
        }

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="localDir">本地文件夹</param>
        /// <param name="localFileName">指定本地保存的文件名</param>
        /// <param name="cosPath">对象在存储桶中的位置标识符，即称对象键  //'文件夹名称/文件key'</param>
        /// <returns></returns>
        public  async Task TransferDownloadObject(string localDir, string localFileName, string cosPath)
        {
            // 初始化 TransferConfig
            TransferConfig transferConfig = new TransferConfig();
            // 手动设置高级下载接口的分块阈值为 20MB(默认为20MB), 从5.4.26版本开始支持！
            //transferConfig.DivisionForDownload = 20 * 1024 * 1024;
            // 手动设置高级下载接口的分块大小为 10MB(默认为5MB),不建议此处设置过小的分块值,可能导致频繁重试或下载速度不合预期
            //transferConfig.SliceSizeForDownload = 10 * 1024 * 1024;

            // 初始化 TransferManager
            TransferManager transferManager = new TransferManager(cosXml, transferConfig);

            //String bucket = "setsail-1307571103"; //存储桶，格式：BucketName-APPID
            //String cosPath = "2022-06-11/HZH_Controls.rar"; //对象在存储桶中的位置标识符，即称对象键  //'文件夹名称/文件key'
            //string localDir = @"D:\cos\";//本地文件夹
            //localFileName = "HZH_Controls.rar"; //指定本地保存的文件名

            // 下载对象
            COSXMLDownloadTask downloadTask = new COSXMLDownloadTask(CookieData.getInstance().bucket, cosPath,
              localDir, localFileName);

            // 手动设置高级下载接口的并发数 (默认为5), 从5.4.26版本开始支持！
            downloadTask.SetMaxTasks(10);
            //执行进度
            //downloadTask.progressCallback = delegate (long completed, long total)
            //{
            //    Console.WriteLine(String.Format("progress = {0:##.##}%", completed * 100.0 / total));
            //};

            try
            {
                COSXMLDownloadTask.DownloadTaskResult result = await
                  transferManager.DownloadAsync(downloadTask);
                //Console.WriteLine(result.GetResultInfo());
                //string eTag = result.eTag;
            }
            catch (COSXML.CosException.CosClientException clientEx)
            {
                //请求失败
                result2 = "CosClientException: " + clientEx;
                //Console.WriteLine("CosClientException: " + clientEx);
            }
            catch (COSXML.CosException.CosServerException serverEx)
            {
                //请求失败
                result2 = "CosServerException: " + serverEx.GetInfo();
                //Console.WriteLine("CosServerException: " + serverEx.GetInfo());
            }
        }
    }
}
